package com.hy.server;

import com.hy.core.ActionListener;
import com.hy.core.util.ByteBufferUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;

/**
 * author: houying
 * date  : 17-6-8
 * desc  :
 */
public class Server {

    private ServerChannelContext serverChannelContext;

    public Server(ServerActionListener listener, ServerHandler serverHandler) throws IOException {
        serverChannelContext = new ServerChannelContext(listener, serverHandler);
    }

    public void start() throws IOException {
        AsynchronousServerSocketChannel serverSocketChannel = serverChannelContext.getServerSocketChannel();
        serverSocketChannel.bind(new InetSocketAddress(9090));
        serverSocketChannel.accept(serverChannelContext, serverChannelContext.getAcceptCompletionHandler());
    }

    public static void main(String[] args) throws IOException {
        ServerHandler<String> handler = new ServerHandler<String>() {
            @Override
            public String decode(ByteBuffer byteBuffer, Session session) {
                return new String(ByteBufferUtils.getBytes(byteBuffer));
            }

            @Override
            public void handle(String pkg) {
                System.out.println(pkg);
            }
        };
        new Server(new ServerActionListener(), handler).start();
    }
}
